package com.example.fget_file;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;

import androidx.arch.core.util.Function;

import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.plugin.common.MethodChannel;


/**
 * 文件扫描工具
 * */
public class FileScanUtil {
    final String TAG = "安卓原生";
    //上下文
    private Context ct;
    // 返回给flutter的数据
    private Map<String,List<FileModel>> map = new HashMap<>();
    private  FileScanUtil utils;
    private List<String> type = new ArrayList<>();
    // flutter主线程的通道返回
    private  MethodChannel.Result result;
    private String path1;

    public FileScanUtil() {

    }


    /**
     * 主线程与子线程通讯
     */
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.what==0)
            {
                Log.d(TAG, "线程结束，收到通知，返回flutter");
                result.success(new Gson().toJson(map));
            }
            return false;
        }
    });


    /**
     * 开始获取文件
     * 创建一个线程扫描文件 防止查询时主线程阻塞 造成UI卡死
     * */
    public void startGetFile(Context ctx, List<String> tp, MethodChannel.Result result1,String path) {
        result = result1;
        ct = ctx;
        type = tp;
        path1 = path;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "进入子线程");
                try {
                    if (path1 == null || path1 == ""){
                        map.put("data", scan(type.toArray(new String[type.size()])));
                    }else{
                        map.put("data",  GetFileName(path1));
                    }
                    // 子线程无法进行更新 通过handler 进行交互
                    Message msg = new Message();
                    msg.what=0;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 使用ContentResolver查询文件
     * */
    private List<FileModel> scan(String[] extension){

        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = new Date();

        List<FileModel> fileModelList = new ArrayList<>();

        ContentResolver resolver = ct.getContentResolver();

        Uri uri = MediaStore.Files.getContentUri("external");

        String where ="";

        // 通过文件类型进行匹配
//        String where = MediaStore.Files.FileColumns.MIME_TYPE + "='image/jpeg'" +
//                " OR " +MediaStore.Files.FileColumns.MIME_TYPE + "='image/png'";
        // 拼接查询条件
        for(int i=0;i<extension.length;i++)
        {
          if(i!=0)
          {
            where = where+" OR ";
          }
          where = where +  MediaStore.Files.FileColumns.DATA+" LIKE '%"+'.'+extension[i]+"'";
        }

        Log.d(TAG, "扫描条件："+where);
        Log.d(TAG, "开始扫描");
        Cursor cursor = resolver.query(
                uri,
                new String[]{MediaStore.Files.FileColumns.DATA,MediaStore.Files.FileColumns.DATE_ADDED,},
                where,
                null,
                MediaStore.Files.FileColumns.DATE_ADDED+" DESC");  //倒叙

        if (cursor != null) {
            while (cursor.moveToNext()) {
                FileModel fileModel = new FileModel();
                File file = new File(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA)));
                date.setTime(file.lastModified());
                fileModel.setFileName(file.getName());
                fileModel.setFilePath(file.getPath());
                fileModel.setFileSize(String.valueOf((file.length() / 1024)%100));
                fileModel.setFileDate(df.format(date));
                fileModelList.add( fileModel );
            }
        }
        Log.d(TAG, "查询数量："+cursor.getCount());
        cursor.close();
        return  fileModelList;
    }


    /**
     * 获取当前目录下所有文件
     * */
    public  List<FileModel> GetFileName(String fileAbsolutePath) {
        File file = new File(fileAbsolutePath);
        File[] subFile = file.listFiles();
        List<FileModel> fileModelList = new ArrayList<>();

        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            // 判断是否为文件夹
            if (!subFile[iFileLength].isDirectory()) {
                FileModel fileModel = new FileModel();
                fileModel.setFileName(subFile[iFileLength].getName());
                fileModel.setFilePath(subFile[iFileLength].getPath());
                fileModel.setFileSize(String.valueOf((subFile[iFileLength].length() / 1024)%100));
                fileModel.setFileDate(String.valueOf(subFile[iFileLength].lastModified()));
                fileModelList.add(fileModel);
            }
        }
        return fileModelList;
    }

}
